package com.jiang.starter.redis.channel;

import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;
import org.springframework.lang.NonNull;

import java.util.Set;

/**
 * 扫描带有@Tpoic注解的接口
 */
public class ClassPathChannelScanner extends ClassPathBeanDefinitionScanner {

    public ClassPathChannelScanner(BeanDefinitionRegistry registry) {
        super(registry, false);
    }

    /**
     * 允许扫描接口
     */
    @Override
    protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
        return beanDefinition.getMetadata().isInterface() && beanDefinition.getMetadata().isIndependent();
    }

    /**
     * 扫描后将bean的类型设置为工厂类型
     * 并传入原始的bean类型
     * 由工厂进行实例化
     */
    @NonNull
    @Override
    protected Set<BeanDefinitionHolder> doScan(@NonNull String... basePackages) {
        Set<BeanDefinitionHolder> beanDefinitionHolders = super.doScan(basePackages);
        for (BeanDefinitionHolder definitionHolder : beanDefinitionHolders) {
            // 获取bean信息
            AbstractBeanDefinition beanDefinition = (AbstractBeanDefinition) definitionHolder.getBeanDefinition();
            String beanClassName = beanDefinition.getBeanClassName();
            // 设置bean工厂
            beanDefinition.setBeanClass(ChannelFactoryBean.class);
            // 设置原始类型
            beanDefinition.getConstructorArgumentValues().addGenericArgumentValue(beanClassName);
        }
        return beanDefinitionHolders;
    }
}
